package com.whut.report;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.whut.model.*;
import com.whut.parMapper.ParProblemCollectDetailMapper;
import com.whut.parMapper.ParProblemDescriptionMapper;
import com.whut.parMapper.ParSystemMapper;
import com.whut.parMapper.utils.MapperUtils;
import com.whut.service.impl.CheckInfoServiceImpl;
import com.whut.service.impl.ReportServiceImpl;
import com.whut.utils.FileUtil;
import com.whut.utils.MDoc;
import com.whut.utils.pointsCalculate;
import com.whut.v_model.ProblemCollectDetail;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class SpecialSafetyReport {
    @Resource
    private UrlProperties urlProperties;
    @Resource
    private Profiles profiles;
    @Resource
    private ParSystemMapper parSystemMapper;
    @Resource
    private ParProblemDescriptionMapper parProblemDescriptionMapper;
    @Resource
    private ParProblemCollectDetailMapper parProblemCollectDetailMapper;
    @Resource
    private CheckInfoServiceImpl checkInfoServiceImpl;
    // @Resource
    @Autowired
    private ReportServiceImpl reportServiceImpl;


    private MapperUtils mapperUtils;

    private int checkId;
    private int projectId;
    private boolean isNew;
    public static final int WIDTH = 718;
    public static final int HEIGHT = 468;
    public SpecialSafetyReport(ParSystemMapper parSystemMapper,
                       ParProblemDescriptionMapper parProblemDescriptionMapper,
                       ParProblemCollectDetailMapper parProblemCollectDetailMapper,
                       CheckInfoServiceImpl checkInfoServiceImpl,
                       ReportServiceImpl reportServiceImpl,
                       MapperUtils mapperUtils,
                       UrlProperties urlProperties,
                       Profiles profiles
    ) {
        this.parSystemMapper = parSystemMapper;
        this.parProblemDescriptionMapper = parProblemDescriptionMapper;
        this.parProblemCollectDetailMapper = parProblemCollectDetailMapper;
        this.checkInfoServiceImpl = checkInfoServiceImpl;
        this.reportServiceImpl = reportServiceImpl;
        this.mapperUtils=mapperUtils;
        this.urlProperties=urlProperties;
        this.urlProperties=urlProperties;
        this.profiles=profiles;

    }
    public String generateReport(int projectId, int checkId, boolean isNew) throws UnsupportedEncodingException {
        Integer taskId = mapperUtils.getContractchecktaskMapper().getTaskIdByCheckId(checkId);
        DecimalFormat df = new DecimalFormat("0.00");
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Date date = new Date();
        DateFormat d1 = new SimpleDateFormat("yyyyMMddhhmmss");
        DateFormat d2 = new SimpleDateFormat("yyyy");
        DateFormat d3 = new SimpleDateFormat("MM");
        DateFormat d4 = new SimpleDateFormat("dd");
        String day = d4.format(date);
        String month = d3.format(date);
        String year = d2.format(date);
        String fileName = d1.format(date);
        dataMap.put("day", day);
        dataMap.put("month", month);
        dataMap.put("year", year);
        List<String> type3List = new ArrayList<String>();
        type3List.add("2");
        type3List.add("3");
        type3List.add("4");
        //工程概况部分，来自ctp的工程信息
        reportServiceImpl.initProjectSummaryFirstPart(projectId, dataMap);
        //工程概况部分，来自设备信息表的设备信息部分
        List<Equipinfo> equipinfoList = mapperUtils.getEquipinfoMapper().getAllByProjectId(projectId);
        String equip = JSON.toJSONString(equipinfoList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
        JSONArray equipArray = JSONArray.parseArray(equip);
        List<Object> equipList = new ArrayList<Object>();
        if (equipArray.size() == 0) {
            Map<String, Object> eqMap = new HashMap<String, Object>();
            eqMap.put("equipType", "\\");
            eqMap.put("equipQua", "\\");
            eqMap.put("equipNum", "\\");
            eqMap.put("equipLeaseUnit", "\\");
            eqMap.put("equipUseUnit", "\\");
            eqMap.put("demolitionUnit", "\\");
            eqMap.put("testUnit", "\\");
            equipList.add(eqMap);
        } else {
            for (int i = 0; i < equipArray.size(); i++) {
                Map<String, Object> eqMap = new HashMap<String, Object>();
                JSONObject equipObject = equipArray.getJSONObject(i);
                eqMap.put("equipType", equipObject.getString("equipType"));
                eqMap.put("equipQua", equipObject.getString("equipQua"));
                eqMap.put("equipNum", equipObject.getString("equipNum"));
                eqMap.put("equipLeaseUnit", equipObject.getString("equipLeaseUnit"));
                eqMap.put("equipUseUnit", equipObject.getString("equipUseUnit"));
                eqMap.put("demolitionUnit", equipObject.getString("demolitionUnit"));
                eqMap.put("testUnit", equipObject.getString("testUnit"));
                equipList.add(eqMap);
            }
        }
        dataMap.put("equipList", equipList);

        //第一部分，（二）分项评估结果
        String ZJname1 = "[1]";
        double allsecondPoint = 0;
        JSONArray ZJname1Array = JSONArray.parseArray(ZJname1);
        float allExtraPointFloat = parProblemCollectDetailMapper.getAllExtraPoint(checkId);
        double allExtraPoint = Double.valueOf(String.valueOf(allExtraPointFloat));
        double overAllPoint = 0;
        List<Object> part2List = new ArrayList<Object>();
        String Name1 = "";
        double allweight1 = 0;
        for (int i = 0; i < ZJname1Array.size(); i++) {
            double Tweight1 = 0;
            String weight1 = parSystemMapper.getWeight1ByName1(parSystemMapper.getName4ByName4Id(ZJname1Array.getIntValue(i)));
            Tweight1 = pointsCalculate.getPercentInstance(weight1);
            allweight1 += Tweight1;
        }
        for (int k = 0; k < ZJname1Array.size(); k++) {
            Map<String, Object> part2Map = new HashMap<String, Object>();
            List<Object> part2InnerList = new ArrayList<Object>();
            String pName1 = parSystemMapper.getName4ByName4Id(ZJname1Array.getIntValue(k));
            double Tweight1 = 0;
            String weight1 = parSystemMapper.getWeight1ByName1(pName1);
            Tweight1 = pointsCalculate.getPercentInstance(weight1);
            if (pName1.equals("安全检查")||pName1.equals("新安全检查")) {
                List<ProblemCollectDetail> list = parProblemCollectDetailMapper.getAllInfoByName1(checkId, pName1);
                dataMap.put("aqLever", pointsCalculate.getMaxRiskPoint(list));
                Name1 = "安全文明";
            } else if (pName1.equals("质量检查")||pName1.equals("新质量检查")) {
                List<ProblemCollectDetail> list = parProblemCollectDetailMapper.getAllInfoByName1(checkId, pName1);
                dataMap.put("zlLever", pointsCalculate.getMaxRiskPoint(list));
                Name1 = "质量隐患";
            } else if (pName1.equals("管理行为")||pName1.equals("新管理行为")) {
                List<ProblemCollectDetail> list = parProblemCollectDetailMapper.getAllInfoByName1(checkId, pName1);
                dataMap.put("glLever", pointsCalculate.getMaxRiskPoint(list));
                Name1 = "管理行为";
            }
            part2Map.put("name1No", k + 1);
            part2Map.put("name1", Name1);
            List<Object> secondIdList = parProblemCollectDetailMapper.getSecondId(checkId, pName1);
            String secondIdInfo = JSON.toJSONString(secondIdList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
            JSONArray secondIdInfoArray = JSONArray.parseArray(secondIdInfo);
            double allweight2 = 0;
            for (int p = 0; p < secondIdInfoArray.size(); p++) {
                int allsecondId = secondIdInfoArray.getIntValue(p);
                String weight2 = parSystemMapper.getWeight3ByThirdId(allsecondId);
                double weight22 = pointsCalculate.getPercentInstance(weight2);
                allweight2 += weight22;
            }
            for (int u = 0; u < secondIdInfoArray.size(); u++) {
                int secondId = secondIdInfoArray.getIntValue(u);
                double weight222 = 0;
                String weight2 = parSystemMapper.getWeight3ByThirdId(secondId);
                weight222 = pointsCalculate.getPercentInstance(weight2);
                List<ProblemCollectDetail> fourthPoints = parProblemCollectDetailMapper.getFourthPoint(checkId, pName1, secondId);
                String fourthCalculateInfo = JSON.toJSONString(fourthPoints, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                JSONArray fourthPointsCalculateArray = JSONArray.parseArray(fourthCalculateInfo);
                double point = 0;
                for (int j = 0; j < fourthPointsCalculateArray.size(); j++) {
                    Map<String, Object> part2InnerMap = new HashMap<String, Object>();
                    JSONObject part2InnerObject = fourthPointsCalculateArray.getJSONObject(j);
                    part2InnerMap.put("pName4", part2InnerObject.getString("pName4"));
                    double weight3 = 0;
                    int part2FourthId = part2InnerObject.getIntValue("fourthId");
                    int part2InnerProblemNum = parProblemCollectDetailMapper.getProblemNumByFourthId(checkId, part2FourthId);
                    int riskPointOver3Num = parProblemCollectDetailMapper.getProblemNumOver3(checkId, part2FourthId, type3List);
                    part2InnerMap.put("problemNum", part2InnerProblemNum);
                    part2InnerMap.put("riskPointNum", riskPointOver3Num);
                    int part2ThirdId = part2InnerObject.getIntValue("thirdId");
//                    weight3 = pointsCalculate.getPercentInstance(part2InnerObject.getString("weight3"));

                    String newWeight3 = mapperUtils.getEditableweightpsMapper().getWeightByNumber(part2ThirdId, taskId);
                    if (StringUtils.isNotBlank(newWeight3)) {
                        weight3 = pointsCalculate.getPercentInstance(newWeight3);
                    } else {
                        weight3 = pointsCalculate.getPercentInstance(part2InnerObject.getString("weight3"));
                    }

                    List<Object> fourthCountList = parProblemCollectDetailMapper.getFourthCountList(checkId, part2ThirdId);
                    String fourthCountInfo = JSON.toJSONString(fourthCountList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                    JSONArray fourthCountInfoArray = JSONArray.parseArray(fourthCountInfo);
                    int countFourthId = fourthCountInfoArray.size();
                    part2InnerMap.put("weight4", pointsCalculate.doubleToPercent(weight3, countFourthId));
                    List<ProblemCollectDetail> sixthPoints = parProblemCollectDetailMapper.getsixthPoints(checkId, part2FourthId);
                    String pointName6Info = JSON.toJSONString(sixthPoints, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                    JSONArray sixthPointsArray = JSONArray.parseArray(pointName6Info);
                    double calculatePoint6 = 0;
                    double calculatePoint66 = 0;
                    double calculateTruePoint = 0;
                    for (int y = 0; y < sixthPointsArray.size(); y++) {
                        JSONObject sixPointObject = sixthPointsArray.getJSONObject(y);
                        int deductSixthId = sixPointObject.getIntValue("sixthId");
                        float deductPointsSumFloat = parProblemCollectDetailMapper.getdeductSum(checkId, deductSixthId);
                        double deductPointsSum = Double.valueOf(String.valueOf(deductPointsSumFloat));
                        double truePoint = Double.parseDouble(sixPointObject.getString("point6"));
                        if (truePoint <= deductPointsSum) {
                            calculatePoint66 = 0;
                        } else {
                            calculatePoint66 = truePoint - deductPointsSum;
                        }
                        calculateTruePoint += truePoint;
                        calculatePoint6 += calculatePoint66;
                    }
                    double noProblemPoint = 0;
                    List<Object> noProblemSixthIdList = mapperUtils.getUncheckeditemsMapper().getNoProblemSixthId(checkId, part2InnerObject.getIntValue("fourthId"));
                    String noProblemSixthIdInfo = JSON.toJSONString(noProblemSixthIdList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                    JSONArray noProblemSixthArray = JSONArray.parseArray(noProblemSixthIdInfo);
                    for (int m = 0; m < noProblemSixthArray.size(); m++) {
                        int noProblemSixthId = noProblemSixthArray.getIntValue(m);
                        double noProblem = Double.parseDouble(parSystemMapper.getPoint4ByPoint4Id(noProblemSixthId));
                        noProblemPoint += noProblem;
                    }
                    double checkItemPoint = (calculatePoint6 + noProblemPoint) / (calculateTruePoint + noProblemPoint) * 100;
                    List<ProblemCollectDetail> checkItemCalcuList = parProblemCollectDetailMapper.getAllFourthInfo(checkId, part2FourthId);
                    String maxFourthRiskPoint = pointsCalculate.getMaxRiskPoint(checkItemCalcuList);
                    int maxFourthRiskPointNum = parProblemCollectDetailMapper.getRiskPointCount(checkId, part2FourthId, maxFourthRiskPoint);
                    double limitFourhPoint = Double.parseDouble((mapperUtils.getPointlimitMapper().getLimitPointByInfo(String.valueOf(maxFourthRiskPointNum), maxFourthRiskPoint)) == null ? "100" : mapperUtils.getPointlimitMapper().getLimitPointByInfo(String.valueOf(maxFourthRiskPointNum), maxFourthRiskPoint));
                    if (checkItemPoint > limitFourhPoint) {
                        checkItemPoint = limitFourhPoint;
                    }
                    String s = df.format(checkItemPoint);
                    part2InnerMap.put("checkItemPoint", s);
                    int allPointSaveFourthPointCount = mapperUtils.getAllpointsaveMapper().getAllPointCountByCheckId(checkId, part2FourthId);
                    if (allPointSaveFourthPointCount != 0) {
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
                        Date date1 = new Date(System.currentTimeMillis());
                        String lastEditTime = formatter.format(date1);
                        mapperUtils.getAllpointsaveMapper().updateAllPoint(checkId, s, part2FourthId, lastEditTime);
                    } else {
                        Allpointsave allpointsave = new Allpointsave();
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
                        Date date1 = new Date(System.currentTimeMillis());
                        allpointsave.setNewCreateTime(formatter.format(date1));
                        allpointsave.setLastEditTime(formatter.format(date1));
                        allpointsave.setProjectId(projectId);
                        allpointsave.setCheckId(checkId);
                        allpointsave.setNumber(part2FourthId);
                        allpointsave.setPoint(s);
                        mapperUtils.getAllpointsaveMapper().insert(allpointsave);
                    }
                    point += checkItemPoint * weight3 / countFourthId;
                    part2InnerList.add(part2InnerMap);
                }

                List<ProblemCollectDetail> noProblemItemList = parProblemCollectDetailMapper.getNoProblemItem(checkId, secondId);
                String noProblemCalculateInfo = JSON.toJSONString(noProblemItemList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                JSONArray noProblemCalculateArray = JSONArray.parseArray(noProblemCalculateInfo);
                for (int j = 0; j < noProblemCalculateArray.size(); j++) {
                    Map<String, Object> part2InnerMap = new HashMap<String, Object>();
                    JSONObject part2InnerObject = noProblemCalculateArray.getJSONObject(j);
//                    part2InnerMap.put("pName4", "无问题项");
                    part2InnerMap.put("pName4", noProblemItemList.get(j).getpName4());
                    double weight3 = 0;
                    int part2FourthId = part2InnerObject.getIntValue("fourthId");
                    int part2InnerProblemNum = parProblemCollectDetailMapper.getProblemNumByFourthId(checkId, part2FourthId);
                    int riskPointOver3Num = parProblemCollectDetailMapper.getProblemNumOver3(checkId, part2FourthId, type3List);
                    part2InnerMap.put("problemNum", part2InnerProblemNum);
                    part2InnerMap.put("riskPointNum", riskPointOver3Num);
                    int part2ThirdId = part2InnerObject.getIntValue("thirdId");
                    //                   weight3 = pointsCalculate.getPercentInstance(part2InnerObject.getString("weight3"));
                    String newWeight3 = mapperUtils.getEditableweightpsMapper().getWeightByNumber(part2ThirdId, taskId);
                    if (StringUtils.isNotBlank(newWeight3)) {
                        weight3 = pointsCalculate.getPercentInstance(newWeight3);
                    } else {
                        weight3 = pointsCalculate.getPercentInstance(part2InnerObject.getString("weight3"));
                    }

                    List<Object> fourthCountList = parProblemCollectDetailMapper.getFourthCountList(checkId, part2ThirdId);
                    String fourthCountInfo = JSON.toJSONString(fourthCountList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                    JSONArray fourthCountInfoArray = JSONArray.parseArray(fourthCountInfo);
                    int countFourthId = fourthCountInfoArray.size();
                    part2InnerMap.put("weight4", pointsCalculate.doubleToPercent(weight3, countFourthId));
                    List<ProblemCollectDetail> sixthPoints = parProblemCollectDetailMapper.getsixthPoints(checkId, part2FourthId);
                    String pointName6Info = JSON.toJSONString(sixthPoints, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                    JSONArray sixthPointsArray = JSONArray.parseArray(pointName6Info);
                    double calculatePoint6 = 0;
                    double calculatePoint66 = 0;
                    double calculateTruePoint = 0;
                    for (int y = 0; y < sixthPointsArray.size(); y++) {
                        JSONObject sixPointObject = sixthPointsArray.getJSONObject(y);
                        int deductSixthId = sixPointObject.getIntValue("sixthId");
                        float deductPointsSumFloat = parProblemCollectDetailMapper.getdeductSum(checkId, deductSixthId);
                        double deductPointsSum = Double.valueOf(String.valueOf(deductPointsSumFloat));
                        double truePoint = Double.parseDouble(sixPointObject.getString("point6"));
                        if (truePoint <= deductPointsSum) {
                            calculatePoint66 = 0;
                        } else {
                            calculatePoint66 = truePoint - deductPointsSum;
                        }
                        calculateTruePoint += truePoint;
                        calculatePoint6 += calculatePoint66;
                    }
                    double noProblemPoint = 0;
                    List<Object> noProblemSixthIdList = mapperUtils.getUncheckeditemsMapper().getNoProblemSixthId(checkId, part2InnerObject.getIntValue("fourthId"));
                    String noProblemSixthIdInfo = JSON.toJSONString(noProblemSixthIdList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                    JSONArray noProblemSixthArray = JSONArray.parseArray(noProblemSixthIdInfo);
                    for (int m = 0; m < noProblemSixthArray.size(); m++) {
                        int noProblemSixthId = noProblemSixthArray.getIntValue(m);
                        double noProblem = Double.parseDouble(parSystemMapper.getPoint4ByPoint4Id(noProblemSixthId));
                        noProblemPoint += noProblem;
                    }
                    double checkItemPoint = (calculatePoint6 + noProblemPoint) / (calculateTruePoint + noProblemPoint) * 100;
                    List<ProblemCollectDetail> checkItemCalcuList = parProblemCollectDetailMapper.getAllFourthInfo(checkId, part2FourthId);
                    String maxFourthRiskPoint = pointsCalculate.getMaxRiskPoint(checkItemCalcuList);
                    int maxFourthRiskPointNum = parProblemCollectDetailMapper.getRiskPointCount(checkId, part2FourthId, maxFourthRiskPoint);
                    double limitFourhPoint = Double.parseDouble((mapperUtils.getPointlimitMapper().getLimitPointByInfo(String.valueOf(maxFourthRiskPointNum), maxFourthRiskPoint)) == null ? "100" : mapperUtils.getPointlimitMapper().getLimitPointByInfo(String.valueOf(maxFourthRiskPointNum), maxFourthRiskPoint));
                    if (checkItemPoint > limitFourhPoint) {
                        checkItemPoint = limitFourhPoint;
                    }
                    String s = df.format(checkItemPoint);
                    part2InnerMap.put("checkItemPoint", s);
                    int allPointSaveFourthPointCount = mapperUtils.getAllpointsaveMapper().getAllPointCountByCheckId(checkId, part2FourthId);
                    if (allPointSaveFourthPointCount != 0) {
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
                        Date date1 = new Date(System.currentTimeMillis());
                        String lastEditTime = formatter.format(date1);
                        mapperUtils.getAllpointsaveMapper().updateAllPoint(checkId, s, part2FourthId, lastEditTime);
                    } else {
                        Allpointsave allpointsave = new Allpointsave();
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
                        Date date1 = new Date(System.currentTimeMillis());
                        allpointsave.setNewCreateTime(formatter.format(date1));
                        allpointsave.setLastEditTime(formatter.format(date1));
                        allpointsave.setProjectId(projectId);
                        allpointsave.setCheckId(checkId);
                        allpointsave.setNumber(part2FourthId);
                        allpointsave.setPoint(s);
                        mapperUtils.getAllpointsaveMapper().insert(allpointsave);
                    }
                    //point += checkItemPoint * weight3 / countFourthId;
                    part2InnerList.add(part2InnerMap);
                }

                List<Object> getThirdId = parProblemCollectDetailMapper.getThirdId(checkId, pName1, secondId);
                String thirdIdInfo = JSON.toJSONString(getThirdId, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                JSONArray thirdArray = JSONArray.parseArray(thirdIdInfo);
                /*thirdArray中还需要加入无问题项的内容*/
                List<Object> noProblemThirdId= mapperUtils.getNoproblemitemMapper().getThirdIdList(checkId,secondId);
                for (Object obj : noProblemThirdId){
                    thirdArray.add(obj);
                }
                double allweight3 = 0;
                for (int v = 0; v < thirdArray.size(); v++) {
                    double Tweight3 = 0;
                    int thirdId = thirdArray.getIntValue(v);
//                    String trueweight3 = parSystemMapper.getWeight3ByThirdId(thirdId);
//                    Tweight3 = pointsCalculate.getPercentInstance(trueweight3);
                    String newWeight3 = mapperUtils.getEditableweightpsMapper().getWeightByNumber(thirdId, taskId);
                    if (StringUtils.isNotBlank(newWeight3)) {
                        Tweight3 = pointsCalculate.getPercentInstance(newWeight3);
                    } else {
                        String trueweight3 = parSystemMapper.getWeight3ByThirdId(thirdId);
                        Tweight3 = pointsCalculate.getPercentInstance(trueweight3);
                    }
                    allweight3 += Tweight3;
                }
                double thirdPoint = Double.parseDouble(df.format(point / allweight3));
                double percent2 = Double.parseDouble(df.format(weight222 / allweight2));
                double secondPoint = Double.parseDouble(df.format(thirdPoint * percent2));
                allsecondPoint += secondPoint;
            }
            if (pName1.equals("安全检查")||pName1.equals("新安全检查")) {
                dataMap.put("aqPoint", allsecondPoint);
            } else if (pName1.equals("质量检查")||pName1.equals("新质量检查")) {
                dataMap.put("zlPoint", allsecondPoint);
            } else if (pName1.equals("管理行为")||pName1.equals("新管理行为")) {
                dataMap.put("glPoint", allsecondPoint);
            }
            int firstPointCount = mapperUtils.getAllpointsaveMapper().getAllPointCountByCheckId(checkId, 1);
            if (firstPointCount != 0) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
                Date date1 = new Date(System.currentTimeMillis());
                String lastEditTime = formatter.format(date1);
                mapperUtils.getAllpointsaveMapper().updateAllPoint(checkId, df.format(allsecondPoint), 1, lastEditTime);
            } else {
                Allpointsave allpointsave = new Allpointsave();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
                Date date1 = new Date(System.currentTimeMillis());
                allpointsave.setNewCreateTime(formatter.format(date1));
                allpointsave.setLastEditTime(formatter.format(date1));
                allpointsave.setCheckId(checkId);
                allpointsave.setNumber(1);
                allpointsave.setPoint(df.format(allsecondPoint));
                allpointsave.setProjectId(projectId);
                mapperUtils.getAllpointsaveMapper().insert(allpointsave);
            }
            double trueWeight1 = Double.parseDouble(df.format(Tweight1 / allweight1));
            overAllPoint += Double.parseDouble(df.format(trueWeight1 * allsecondPoint));
            part2Map.put("point", allsecondPoint);
            part2Map.put("part2InnerList", part2InnerList);
            part2List.add(part2Map);
        }
        List<ProblemCollectDetail> overallList = parProblemCollectDetailMapper.getAllProblemCollectInfoByCheckId(checkId);
        ContractTaskProject contractTaskProjectRiskPoint = new ContractTaskProject();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date date1 = new Date(System.currentTimeMillis());
        contractTaskProjectRiskPoint.setLastEditTime(formatter.format(date1));
        contractTaskProjectRiskPoint.setProjectId(projectId);
        contractTaskProjectRiskPoint.setLatestRiskLevel(pointsCalculate.getMaxRiskPoint(overallList));
        mapperUtils.getContractTaskProjectMapper().updateByPrimaryKeySelective(contractTaskProjectRiskPoint);
        ContractTaskProject newRiskList = mapperUtils.getContractTaskProjectMapper().selectByPrimaryKey(projectId);
        String finishTime = mapperUtils.getContractchecktaskMapper().getFinishTimeByCheckId(checkId);
        if (newRiskList.getCheckTime().equals("") || newRiskList.getCheckTime().compareTo(finishTime) <= 0) {
            try {
                ContractTaskProject contracttaskproject = new ContractTaskProject();
                contracttaskproject.setLastEditTime(formatter.format(date1));
                contracttaskproject.setProjectId(projectId);
                contracttaskproject.setLatestCheckTime(finishTime);
                mapperUtils.getContractTaskProjectMapper().updateByPrimaryKeySelective(contracttaskproject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        dataMap.put("part2List", part2List);


        //分项评估结果与综合评估结果
        List<Integer> ZJThirdIdList = parProblemCollectDetailMapper.getAllZJthirdId(checkId, 1385);
        List<Object> ZJList = new ArrayList<Object>();
        for (int t = 0; t < ZJThirdIdList.size(); t++) {
            Map<String, Object> ZJMap = new HashMap<String, Object>();
            ZJMap.put("aqPoint", "\\");
            ZJMap.put("hjPoint", "\\");
            String ZJtype = "";
            double ZJallOverPoint = 0;
            double ZJthirdPoint = 0;
            double ZJaqPoint = 0;
            double ZJhjPoint = 0;
            ZJMap.put("thirdPoint", "\\");
            ZJMap.put("No", t + 1);
            ZJMap.put("aqAllPoint", allsecondPoint);
            ZJMap.put("pName3", parSystemMapper.getName4ByName4Id(ZJThirdIdList.get(t)));
            switch (parSystemMapper.getName4ByName4Id(ZJThirdIdList.get(t))) {
                case "项目公司":
                    ZJtype = "投资管理";
                    break;
                case "监理":
                    ZJtype = "投资管理";
                    break;
                case "施工总承包(投资管理)":
                    ZJtype = "投资管理";
                    break;
                case "指挥部":
                    ZJtype = "EPC咨询管理";
                    break;
                case "施工总承包":
                    ZJtype = "EPC咨询管理";
                    break;
                case "工程总承包项目部":
                    ZJtype = "EPC工程总承包管理";
                    break;
                case "PC工厂":
                    ZJtype = "PC生产管理";
                    break;
                default:
                    ZJtype = "";
                    break;
            }
            ZJMap.put("problemNum", parProblemCollectDetailMapper.getProblemNumByThirdId(checkId, ZJThirdIdList.get(t)));
            ZJMap.put("riskPoint", parProblemCollectDetailMapper.getRiskPointNumOver3ByThirdId(checkId, ZJThirdIdList.get(t), type3List));
            List<ProblemCollectDetail> ZJfourthPoints = parProblemCollectDetailMapper.getZJFourthPoint(checkId, ZJThirdIdList.get(t));
            String ZJfourthCalculateInfo = JSON.toJSONString(ZJfourthPoints, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
            JSONArray ZJfourthPointsCalculateArray = JSONArray.parseArray(ZJfourthCalculateInfo);
            for (int j = 0; j < ZJfourthPointsCalculateArray.size(); j++) {
                JSONObject ZJpart2InnerObject = ZJfourthPointsCalculateArray.getJSONObject(j);
                int ZJpart2FourthId = ZJpart2InnerObject.getIntValue("fourthId");
                List<ProblemCollectDetail> ZJsixthPoints = parProblemCollectDetailMapper.getZJsixthPoints(checkId, ZJpart2FourthId);
                String ZJpointName6Info = JSON.toJSONString(ZJsixthPoints, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                JSONArray ZJsixthPointsArray = JSONArray.parseArray(ZJpointName6Info);
                double ZJcalculatePoint6 = 0;
                double ZJcalculatePoint66 = 0;
                double ZJcalculateTruePoint = 0;
                for (int y = 0; y < ZJsixthPointsArray.size(); y++) {
                    JSONObject ZJsixPointObject = ZJsixthPointsArray.getJSONObject(y);
                    int ZJdeductSixthId = ZJsixPointObject.getIntValue("sixthId");
                    float ZJdeductPointsSumFloat = parProblemCollectDetailMapper.getdeductSum(checkId, ZJdeductSixthId);
                    double ZJdeductPointsSum = Double.valueOf(String.valueOf(ZJdeductPointsSumFloat));
                    double ZJtruePoint = Double.parseDouble(ZJsixPointObject.getString("point6"));
                    if (ZJtruePoint <= ZJdeductPointsSum) {
                        ZJcalculatePoint66 = 0;
                    } else {
                        ZJcalculatePoint66 = ZJtruePoint - ZJdeductPointsSum;
                    }
                    ZJcalculateTruePoint += ZJtruePoint;
                    ZJcalculatePoint6 += ZJcalculatePoint66;
                }
                double ZJnoProblemPoint = 0;
                List<Object> ZJnoProblemSixthIdList = mapperUtils.getUncheckeditemsMapper().getNoProblemSixthId(checkId, ZJpart2FourthId);
                String ZJnoProblemSixthIdInfo = JSON.toJSONString(ZJnoProblemSixthIdList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                JSONArray ZJnoProblemSixthArray = JSONArray.parseArray(ZJnoProblemSixthIdInfo);
                for (int m = 0; m < ZJnoProblemSixthArray.size(); m++) {
                    int ZJnoProblemSixthId = ZJnoProblemSixthArray.getIntValue(m);
                    double ZJnoProblem = Double.parseDouble(parSystemMapper.getPoint4ByPoint4Id(ZJnoProblemSixthId));
                    ZJnoProblemPoint += ZJnoProblem;
                }
                double ZJcheckItemPoint = (ZJcalculatePoint6 + ZJnoProblemPoint) / (ZJcalculateTruePoint + ZJnoProblemPoint) * 100;
                List<ProblemCollectDetail> ZJcheckItemCalcuList = parProblemCollectDetailMapper.getAllFourthInfo(checkId, ZJpart2FourthId);
                String ZJmaxFourthRiskPoint = pointsCalculate.getMaxRiskPoint(ZJcheckItemCalcuList);
                int ZJmaxFourthRiskPointNum = parProblemCollectDetailMapper.getRiskPointCount(checkId, ZJpart2FourthId, ZJmaxFourthRiskPoint);
                double ZJlimitFourthPoint = Double.parseDouble((mapperUtils.getPointlimitMapper().getLimitPointByInfo(String.valueOf(ZJmaxFourthRiskPointNum), ZJmaxFourthRiskPoint)) == null ? "100" : mapperUtils.getPointlimitMapper().getLimitPointByInfo(String.valueOf(ZJmaxFourthRiskPointNum), ZJmaxFourthRiskPoint));
                if (ZJcheckItemPoint > ZJlimitFourthPoint) {
                    ZJcheckItemPoint = ZJlimitFourthPoint;
                }
                String s = df.format(ZJcheckItemPoint);
                if (parSystemMapper.getName4ByName4Id(ZJpart2FourthId).equals("安全文明")) {
                    ZJaqPoint = ZJcheckItemPoint;
                    ZJMap.put("aqPoint", s);
                } else if (parSystemMapper.getName4ByName4Id(ZJpart2FourthId).equals("环境管理")) {
                    ZJhjPoint = ZJcheckItemPoint;
                    ZJMap.put("hjPoint", s);
                }
            }
            if (ZJfourthPointsCalculateArray.size() == 1) {
                ZJthirdPoint = ZJaqPoint + ZJhjPoint;
            } else if (ZJfourthPointsCalculateArray.size() == 2) {
                ZJthirdPoint = ZJaqPoint * 0.7 + ZJhjPoint * 0.3;
            }
            ZJMap.put("type", ZJtype);
            String ZJthird = df.format(ZJthirdPoint);
            ZJMap.put("thirdPoint", ZJthird);
            ZJallOverPoint = allsecondPoint * 0.7 + ZJthirdPoint * 0.3;
            String ZJallOver = df.format(ZJallOverPoint);
            ZJMap.put("allOverPoint", ZJallOver);
            ZJList.add(ZJMap);
        }
        dataMap.put("ZJList", ZJList);
        //改进建议（小结）
        List<Integer> pName1Info = parProblemCollectDetailMapper.getAllName1Id(checkId);
        String name1 = JSON.toJSONString(pName1Info, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
        JSONArray name1Array = JSONArray.parseArray(name1);
        List<Object> part4List = new ArrayList<Object>();
        for (int i = 0; i < name1Array.size(); i++) {
            List<Object> part4InnerList = new ArrayList<Object>();
            Map<String, Object> part4Map = new HashMap<String, Object>();
            String pName1 = parSystemMapper.getName4ByName4Id(name1Array.getIntValue(i));
            List<Summary> summaryList = mapperUtils.getSummaryMapper().getSummaryInfo(checkId, name1Array.getIntValue(i));
            String summaryInfo = JSON.toJSONString(summaryList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
            JSONArray summaryInfoArray = JSONArray.parseArray(summaryInfo);
            for (int j = 0; j < summaryInfoArray.size(); j++) {
                Map<String, Object> part4InnerMap = new HashMap<String, Object>();
                JSONObject part4InnerObject = summaryInfoArray.getJSONObject(j);
                String part4pNname4 = parSystemMapper.getName4ByName4Id(part4InnerObject.getIntValue("fourthId"));
                part4InnerMap.put("No", j + 1);
                if (parSystemMapper.getFather(parSystemMapper.getFather(part4InnerObject.getIntValue("fourthId")).getPreNum()).getPreNum() == 1385) {
                    part4InnerMap.put("pName4", part4pNname4 + "(" + parSystemMapper.getFather(parSystemMapper.getFather(part4InnerObject.getIntValue("fourthId")).getPreNum()).getParameterName() + ")");
                } else {
                    part4InnerMap.put("pName4", part4pNname4);
                }
                part4InnerMap.put("summary", part4InnerObject.getString("summary"));
                part4InnerList.add(part4InnerMap);
            }
            if (pName1.equals("安全检查")||pName1.equals("新安全检查")) {
                part4Map.put("name1", "安全");
            } else if (pName1.equals("质量检查")||pName1.equals("新质量检查")) {
                part4Map.put("name1", "质量");
            } else if (pName1.equals("管理行为")||pName1.equals("新管理行为")) {
                part4Map.put("name1", "管理行为");
            }
            part4Map.put("part4InnerList", part4InnerList);
            part4List.add(part4Map);
        }
        dataMap.put("part4List", part4List);
        //第二部分 不符合项清单
        List<ProblemCollectDetail> problemList = parProblemCollectDetailMapper.getAllProblemCollectInfoByCheckId(checkId);
        List<Object> section22List = new ArrayList<Object>();
        for (int p = 0; p < problemList.size(); p++) {
            Map<String, Object> problemListMap = new HashMap<String, Object>();
            problemListMap.put("No", p + 1);
            if (problemList.get(p).getSecondId() == 1385) {
                problemListMap.put("pName4", problemList.get(p).getpName4() + "(" + problemList.get(p).getpName3() + ")");
            } else {
                problemListMap.put("pName4", problemList.get(p).getpName4());
            }
            if (problemList.get(p).getIsRemark().equals("N")) {
                problemListMap.put("problemDescription", problemList.get(p).getProblemDescription());
            } else if (problemList.get(p).getIsRemark().equals("Y")) {
                problemListMap.put("problemDescription", problemList.get(p).getRemark());
            }
            String problemListRiskPoint = "";
            switch (problemList.get(p).getRiskPoint()) {
                case "提醒":
                    problemListRiskPoint = "提醒";
                    break;
                case "1":
                    problemListRiskPoint = "四级隐患";
                    break;
                case "2":
                    problemListRiskPoint = "三级隐患";
                    break;
                case "3":
                    problemListRiskPoint = "二级隐患";
                    break;
                case "4":
                    problemListRiskPoint = "一级隐患";
                    break;
                default:
                    problemListRiskPoint = "";
                    break;
            }
            problemListMap.put("riskPoint", problemListRiskPoint);
            section22List.add(problemListMap);
        }
        dataMap.put("section22List", section22List);

        //第三部分，各部分工程检查情况
        List<Object> section2pName1Info = parProblemCollectDetailMapper.getAllName1IdForType3Report(checkId, type3List);
        String section2Name1 = JSON.toJSONString(section2pName1Info, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
        JSONArray section2Name1Array = JSONArray.parseArray(section2Name1);
        String section2pName1 = "";
        List<Object> section2List = new ArrayList<Object>();
        for (int b = 0; b < section2Name1Array.size(); b++) {
            Map<String, Object> section2Name1Map = new HashMap<String, Object>();
            List<Object> section2name1List = new ArrayList<Object>();
            String section2name1 = parSystemMapper.getName4ByName4Id(section2Name1Array.getIntValue(b));
            if (section2name1.equals("安全检查")||section2name1.equals("新安全检查")) {
                section2pName1 = "安全问题";
            } else if (section2name1.equals("质量检查")||section2name1.equals("新质量检查")) {
                section2pName1 = "质量问题";
            } else if (section2name1.equals("管理行为")||section2name1.equals("新管理行为")) {
                section2pName1 = "管理体系及管理动作";
            }
            section2Name1Map.put("section2pName1", section2pName1);
            List<Object> section2Name4Info = parProblemCollectDetailMapper.getAllName4ByName1ForType3(checkId, section2name1, type3List);
            String section2Name44 = JSON.toJSONString(section2Name4Info, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
            JSONArray section2Name4Array = JSONArray.parseArray(section2Name44);
            for (int w = 0; w < section2Name4Array.size(); w++) {
                Map<String, Object> section2Name4Map = new HashMap<String, Object>();
                List<Object> section2Name4List = new ArrayList<Object>();
                int section2Name4Id = section2Name4Array.getIntValue(w);
                String section2Name4 = parSystemMapper.getName4ByName4Id(section2Name4Id);
                List<ProblemCollectDetail> section2Name6Info = parProblemCollectDetailMapper.getAllName6InfoByName4ForType3(checkId, section2Name4Id, section2name1, type3List);
                String section2Name66 = JSON.toJSONString(section2Name6Info, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                JSONArray section2Name6Array = JSONArray.parseArray(section2Name66);
                for (int c = 0; c < section2Name6Array.size(); c++) {
                    Map<String, Object> section2Name6Map = new HashMap<String, Object>();
                    List<Object> picList = new ArrayList<Object>();
                    JSONObject section2Name6Object = section2Name6Array.getJSONObject(c);
                    section2Name6Map.put("section2pName6No", c + 1);
                    section2Name6Map.put("section2pName6", section2Name6Object.getString("pName6"));
                    section2Name6Map.put("section2pName5", section2Name6Object.getString("pName5"));
                    String section2RiskPoint = "";
                    switch (section2Name6Object.getString("riskPoint")) {
                        case "1":
                            section2RiskPoint = "四级隐患";
                            break;
                            case "2":
                            section2RiskPoint = "三级隐患";
                            break;
                        case "3":
                            section2RiskPoint = "二级隐患";
                            break;
                        case "4":
                            section2RiskPoint = "一级隐患";
                            break;
                        default:
                            section2RiskPoint = "四级隐患";
                            break;
                    }
                    section2Name6Map.put("section2RiskLevel", section2RiskPoint);
                    section2Name6Map.put("section2CheckPart", section2Name6Object.getString("checkPart"));
                    section2Name6Map.put("section2ProblemNum", section2Name6Object.getString("problemQua"));
                    if (section2Name6Object.getString("isRemark").equals("N")) {
                        section2Name6Map.put("section2problemDescription", section2Name6Object.getString("problemDescription"));
                    } else if (section2Name6Object.getString("isRemark").equals("Y")) {
                        section2Name6Map.put("section2problemDescription", section2Name6Object.getString("remark"));
                    }
                    section2Name6Map.put("section2normsProvison", section2Name6Object.getString("normsProvison"));
                    section2Name6Map.put("section2suggestion", section2Name6Object.getString("suggestion"));
                    String section2picPath = section2Name6Object.getString("picPath");
                    String picName = section2Name6Object.getString("picName");
                    JSONArray ja = JSONArray.parseArray(picName);
                    if (ja.size() == 0) {
                        //String s = MDoc.getImageStr("C:\\Users\\96500\\Desktop\\20190329183836002.png");
                        String s = MDoc.getImageStr("D:\\whutServer\\generatedCharts\\noPic.png");
//                        String s = MDoc.getImageStr("D:\\WAAA\\新建文件夹\\QQ截图20200819114048.jpg");

                        picList.add(s);
                    } else {
                        for (int o = 0; o < ja.size(); o++) {
                            String s = "";
                            if ("prod".equals(profiles.getActives())) {
                                s = MDoc.getImageStr(section2picPath + ja.getString(o));
                            }
//                            String s = MDoc.getImageStr("D:\\WAAA\\新建文件夹\\QQ截图20200819114048.jpg" + ja.getString(o));
                            //String s = MDoc.getImageStr("C:\\Users\\96500\\Desktop\\20190329183836002.png");
                            picList.add(s);
                        }
                    }
                    section2Name6Map.put("picList", picList);
                    section2Name4List.add(section2Name6Map);

                }
                if (parSystemMapper.getFather(section2Name4Id).getPreNum() == 1385) {
                    section2Name4Map.put("section2pName4", section2Name4 + "(" + parSystemMapper.getFather(section2Name4Id).getParameterName() + ")");
                } else {
                    section2Name4Map.put("section2pName4", section2Name4);
                }
                section2Name4Map.put("section2Name4List", section2Name4List);
                section2name1List.add(section2Name4Map);
            }
            section2Name1Map.put("section2Name1List", section2name1List);
            section2List.add(section2Name1Map);
        }
        dataMap.put("section2List", section2List);
        MDoc mdoc = new MDoc();
        String path = FileUtil.getServerFolderPath();
        File f1 = new File(path, "doc");
        if (!f1.exists()) {
            f1.mkdirs();
        }
//        mdoc.createDoc(dataMap, "D:\\WAAA\\新建文件夹\\" + dataMap.get("projectName").toString().replace('#','号')+"安全专项报告"+fileName + ".doc", "ftl\\ZJ1.0.ftl");
//        MDoc.docToDocx("D:\\WAAA\\新建文件夹\\" + dataMap.get("projectName").toString().replace('#','号')+"安全专项报告"+fileName + ".doc", "D:\\WAAA\\新建文件夹\\" + dataMap.get("projectName").toString().replace('#','号')+"安全专项报告"+fileName + ".doc");
//        String result = "D:\\ WAAA\\新建文件夹\\" + dataMap.get("projectName").toString().replace('#','号')+"安全专项报告"+fileName + ".doc";
        mdoc.createDoc(dataMap, path + "\\doc\\" + dataMap.get("projectName").toString().replace('#', '号') + "安全专项报告" + fileName + ".doc", "ftl\\ZJ1.0.ftl");
        //MDoc.docToDocx("D:\\whutServer\\apache-tomcat-8.5.41\\webapps\\ROOT\\doc\\" + dataMap.get("projectName").toString().replace('#','号')+"安全专项报告"+fileName + ".doc", "D:\\whutServer\\apache-tomcat-8.5.41\\webapps\\ROOT\\doc\\" + dataMap.get("projectName").toString().replace('#','号')+"安全专项报告"+fileName + ".doc");
        String result = urlProperties.getAddress() + "/doc/" + dataMap.get("projectName").toString().replace('#', '号') + "安全专项报告" + fileName + ".doc";
        return result;
    }
}
